package com.liver_cloud.util;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BeanUtils {

	public static Map<String, Object> objectToMap(Object obj) {
		if (obj == null) {
			return null;
		}
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			// 获取关联的所有类，本类以及所有父类
			boolean ret = true;
			Class oo = obj.getClass();
			List<Class> clazzs = new ArrayList<Class>();
			while (ret) {
				clazzs.add(oo);
				oo = oo.getSuperclass();
				if (oo == null || oo == Object.class)
					break;
			}

			for (int i = 0; i < clazzs.size(); i++) {
				Field[] declaredFields = clazzs.get(i).getDeclaredFields();
				for (Field field : declaredFields) {
					int mod = field.getModifiers();
					// 过滤 static 、 final 类型 以及过滤值为null的属性
					if (Modifier.isStatic(mod) || Modifier.isFinal(mod) || field.get(obj) == null) {
						continue;
					}

					field.setAccessible(true);
					map.put(field.getName(), field.get(obj));
				}
			}
		} catch (IllegalArgumentException | IllegalAccessException e) {
			e.printStackTrace();
		}
		return map;
	}
}
